#define _XOPEN_SOURCE
#include <stdio.h>
#include <string.h>
#include "userinfo.h"
#include <time.h>
#include "../cJson/cJSON.h"
#include "ui.h"



User users[MAX_USERS];
int user_count = 0;
int current_user_index = -1;  



// int load_user_by_phone(const char *phone) {
//     FILE *fp = fopen("userinfo.txt", "r");
//     if (!fp) {
//         printf("⚠️ 无法打开 userinfo.txt 文件\n");
//         return 0;  // 文件不存在也算未注册
//     }

//     char line[128];
//     while (fgets(line, sizeof(line), fp)) {
//         // 去掉末尾换行符
//         line[strcspn(line, "\r\n")] = '\0';

//         // 第1行：手机号
//         if (strcmp(line, phone) == 0) {
//             fclose(fp);
//             return 1;  // 已找到，手机号已注册
//         }

//         // 跳过接下来的3行（密码、会员号、时间）
//         for (int i = 0; i < 3; ++i) {
//             if (!fgets(line, sizeof(line), fp)) break;
//         }
//     }

//     fclose(fp);
//     return 0;  // 未找到，手机号未注册
// }

void load_users_from_json(const char *filename) {
    FILE *fp = fopen(filename, "r");
    if (!fp) {
        printf("No user file found.\n");
        return;
    }

    fseek(fp, 0, SEEK_END);
    long len = ftell(fp);
    rewind(fp);

    char *data = malloc(len + 1);
    fread(data, 1, len, fp);
    data[len] = '\0';
    fclose(fp);

    cJSON *root = cJSON_Parse(data);
    free(data);
    if (!root || !cJSON_IsArray(root)) return;

    user_count = 0;
    int size = cJSON_GetArraySize(root);
    for (int i = 0; i < size && user_count < MAX_USERS; ++i) {
        cJSON *item = cJSON_GetArrayItem(root, i);
        User *u = &users[user_count];

        strcpy(u->phone, cJSON_GetObjectItem(item, "phone")->valuestring);
        strcpy(u->password, cJSON_GetObjectItem(item, "password")->valuestring);
        strcpy(u->register_time, cJSON_GetObjectItem(item, "register_time")->valuestring);
        strcpy(u->member_id, cJSON_GetObjectItem(item, "member_id")->valuestring);
        u->balance = cJSON_GetObjectItem(item, "balance")->valuedouble;

        u->ticket_count = 0;
        cJSON *tickets = cJSON_GetObjectItem(item, "tickets");
        if (tickets && cJSON_IsArray(tickets)) {
            int tsize = cJSON_GetArraySize(tickets);
            for (int j = 0; j < tsize && j < 10; ++j) {
                cJSON *ticket = cJSON_GetArrayItem(tickets, j);
                strcpy(u->tickets[j].movie_name, cJSON_GetObjectItem(ticket, "movie_name")->valuestring);
                strcpy(u->tickets[j].show_time, cJSON_GetObjectItem(ticket, "show_time")->valuestring);
                u->ticket_count++;
            }
        }

        user_count++;
    }

    cJSON_Delete(root);
}

User *find_user_by_phone(const char *phone) {
    for (int i = 0; i < user_count; ++i) {
        if (strcmp(users[i].phone, phone) == 0) {
            return &users[i];
        }
    }
    return NULL;
}


void generate_vip_card(char *dest, int max_len) {
    static int counter = 1000;  // 简单计数方式，确保唯一性（生产系统中需替代）
    snprintf(dest, max_len, "VIP%06d", counter++);
}

void get_current_time_str(char *buf, int buf_size) {
    time_t now = time(NULL);
    struct tm *t = localtime(&now);
    strftime(buf, buf_size, "%Y-%m-%d %H:%M", t);
}

// int save_user_info(const char *phone, const char *password) {
//     FILE *fp = fopen("userinfo.txt", "a");
//     if (!fp) return -1;

//     char vip[16], time_str[32];
//     generate_vip_card(vip, sizeof(vip));
//     get_current_time_str(time_str, sizeof(time_str));

//     fprintf(fp, "%s\n%s\n%s\n%s\n", phone, password, vip, time_str);

//     fclose(fp);
//     return 0;
// }

void save_users_to_json(const char *filename) {
    cJSON *root = cJSON_CreateArray();

    for (int i = 0; i < user_count; ++i) {
        User *u = &users[i];
        cJSON *item = cJSON_CreateObject();
        cJSON_AddStringToObject(item, "phone", u->phone);
        cJSON_AddStringToObject(item, "password", u->password);
        cJSON_AddStringToObject(item, "register_time", u->register_time);
        cJSON_AddStringToObject(item, "member_id", u->member_id);
        cJSON_AddNumberToObject(item, "balance", u->balance);

        cJSON *ticket_arr = cJSON_CreateArray();
        for (int j = 0; j < u->ticket_count; ++j) {
            cJSON *tk = cJSON_CreateObject();
            cJSON_AddStringToObject(tk, "movie_name", u->tickets[j].movie_name);
            cJSON_AddStringToObject(tk, "show_time", u->tickets[j].show_time);
            cJSON_AddStringToObject(tk, "seat", u->tickets[j].seat);
            cJSON_AddItemToArray(ticket_arr, tk);
        }

        cJSON_AddItemToObject(item, "tickets", ticket_arr);
        cJSON_AddItemToArray(root, item);
    }

    char *json_str = cJSON_Print(root);
    FILE *fp = fopen(filename, "w");
    if (fp) {
        fputs(json_str, fp);
        fclose(fp);
    }

    free(json_str);
    cJSON_Delete(root);
}

int verify_login(const char *phone, const char *password) {
    for (int i = 0; i < user_count; ++i) {
        if (strcmp(users[i].phone, phone) == 0) {
            if (strcmp(users[i].password, password) == 0) {
                current_user_index = i;  // ✅ 设置当前用户下标！
                return 1;  // 登录成功
            } else {
                return 0;  // 密码错误
            }
        }
    }
    return 0;  // 用户不存在
}


void display_user_tickets(const char *phone) {
    FILE *fp = fopen("userinfo.json", "r");
    if (!fp) {
        printf("无法打开用户信息文件\n");
        lv_label_set_text(ui_getTKListLab, "无法读取用户信息");
        return;
    }

    // 读取整个文件内容
    fseek(fp, 0, SEEK_END);
    long length = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    char *data = malloc(length + 1);
    if (!data) {
        fclose(fp);
        printf("内存分配失败\n");
        return;
    }
    fread(data, 1, length, fp);
    data[length] = '\0';
    fclose(fp);

    // 解析 JSON
    cJSON *root = cJSON_Parse(data);
    free(data);
    if (!root) {
        printf("JSON 解析失败\n");
        lv_label_set_text(ui_getTKListLab, "数据错误");
        return;
    }

    cJSON *user;
    cJSON_ArrayForEach(user, root) {
        cJSON *user_phone = cJSON_GetObjectItem(user, "phone");
        if (!user_phone || strcmp(user_phone->valuestring, phone) != 0)
            continue;

        cJSON *tickets = cJSON_GetObjectItem(user, "tickets");
        if (!tickets || !cJSON_IsArray(tickets)) {
            lv_label_set_text(ui_getTKListLab, "No Ticket record!");
            cJSON_Delete(root);
            return;
        }

        char buffer[1024] = "";
        cJSON *ticket;
        cJSON_ArrayForEach(ticket, tickets) {
            cJSON *movie = cJSON_GetObjectItem(ticket, "movie_name");
            if (movie && cJSON_IsString(movie)) {
                strcat(buffer, movie->valuestring);
                strcat(buffer, "\n");
            }
        }

        lv_label_set_text(ui_getTKListLab, *buffer ? buffer : "No Ticket record!");
        cJSON_Delete(root);
        return;
    }

    // 如果手机号未找到
    lv_label_set_text(ui_getTKListLab, "User Error!");
    cJSON_Delete(root);
}

static void save_json_to_file(cJSON *root, const char *filename) {
    char *out = cJSON_Print(root);
    FILE *fp = fopen(filename, "w");
    if (fp) {
        fputs(out, fp);
        fclose(fp);
    }
    free(out);
}

void delete_all_tickets(const char *phone) {
    FILE *fp = fopen("userinfo.json", "r");
    if (!fp) return;

    fseek(fp, 0, SEEK_END);
    long size = ftell(fp);
    rewind(fp);

    char *data = malloc(size + 1);
    fread(data, 1, size, fp);
    data[size] = '\0';
    fclose(fp);

    cJSON *root = cJSON_Parse(data);
    free(data);
    if (!root) return;

    cJSON *user;
    cJSON_ArrayForEach(user, root) {
        cJSON *user_phone = cJSON_GetObjectItem(user, "phone");
        if (user_phone && strcmp(user_phone->valuestring, phone) == 0) {
            cJSON *tickets = cJSON_GetObjectItem(user, "tickets");
            if (tickets) {
                cJSON_ReplaceItemInObject(user, "tickets", cJSON_CreateArray());
            }
            break;
        }
    }

    save_json_to_file(root, "userinfo.json");
    cJSON_Delete(root);
}


// void delete_expired_tickets(const char *phone) {
//     FILE *fp = fopen("userinfo.json", "r");
//     if (!fp) return;

//     fseek(fp, 0, SEEK_END);
//     long size = ftell(fp);
//     rewind(fp);

//     char *data = malloc(size + 1);
//     fread(data, 1, size, fp);
//     data[size] = '\0';
//     fclose(fp);

//     cJSON *root = cJSON_Parse(data);
//     free(data);
//     if (!root) return;

//     time_t now = time(NULL);

//     cJSON *user;
//     cJSON_ArrayForEach(user, root) {
//         cJSON *user_phone = cJSON_GetObjectItem(user, "phone");
//         if (!user_phone || strcmp(user_phone->valuestring, phone) != 0)
//             continue;

//         cJSON *tickets = cJSON_GetObjectItem(user, "tickets");
//         if (!tickets || !cJSON_IsArray(tickets))
//             break;

//         cJSON *valid_tickets = cJSON_CreateArray();
//         cJSON *ticket;
//         cJSON_ArrayForEach(ticket, tickets) {
//             cJSON *time_item = cJSON_GetObjectItem(ticket, "time");
//             if (!cJSON_IsString(time_item)) continue;

//             struct tm tm = {0};
//             strptime(time_item->valuestring, "%Y-%m-%d %H:%M", &tm);
//             time_t ticket_time = mktime(&tm);

//             if (difftime(ticket_time, now) > 0) {
//                 cJSON_AddItemToArray(valid_tickets, cJSON_Duplicate(ticket, 1));
//             }
//         }

//         cJSON_ReplaceItemInObject(user, "tickets", valid_tickets);
//         break;
//     }

//     save_json_to_file(root, "userinfo.json");
//     cJSON_Delete(root);
// }

User *get_current_user() {
    if (current_user_index >= 0 && current_user_index < user_count) {
        return &users[current_user_index];
    }
    return NULL;
}


